package com.ruihu.admin.common.mybatis;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedTypes(value = List.class)
@MappedJdbcTypes(value = JdbcType.VARCHAR)
public class StringToLongListHandler extends BaseTypeHandler<List<Long>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Long> values, JdbcType jdbcType) throws SQLException {
        String s = CollectionUtil.join(values, StrUtil.COMMA);
        ps.setString(i, s);
    }

    @Override
    public List<Long> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return stringToList(resultSet.getString(s));
    }

    @Override
    public List<Long> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return stringToList(resultSet.getString(i));
    }

    @Override
    public List<Long> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return stringToList(callableStatement.getString(i));
    }

    private List<Long> stringToList(String str) {
        List<Long> list = new ArrayList<>();
        if (StrUtil.isNotEmpty(str)) {
            long[] arr = StrUtil.splitToLong(str, StrUtil.COMMA);
            for (long v : arr)
                list.add(v);
        }
        return list;
    }
}
